package com.maoshi.shop.scoremall.api.listener;

import com.maoshi.shop.service.UserExtensionService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 支付时判断积分是否足够事件
 */
@Component("scoreOrderListener")
@AllArgsConstructor
public class ScoreOrderListener {

    private UserExtensionService userExtensionService;

//    /**
//     *  支付时判断积分是否足够事件
//     */
//    @EventListener(ScoreIsEnoughEvent.class)
//    public void scoreCouponOrderListener(ScoreIsEnoughEvent event) {
//        Order order = event.getOrderDb();
//        UserExtension userExtension = userExtensionService.getOne(new LambdaUpdateWrapper<UserExtension>().eq(UserExtension::getUserId, order.getUserId()));
//        List<OrderSettlement> orderSettlements = event.getOrderSettlements();
//        OrderSettlement orderSettlement = orderSettlements.get(0);
//        //1.如果是积分订单
//        if(ObjectUtil.equal(order, OrderType.SCORE.value()) && userExtension.getScore() < orderSettlement.getPayScore()){
//                throw new MaoshiShopBindException("用户积分不足，无法进行支付");
//        }
//        //1.如果是普通订单
//        int totalScore = 0;
//        for (OrderSettlement settlement : orderSettlements) {
//            totalScore += settlement.getPayScore() == null ?0:settlement.getPayScore();
//        }
//        if(userExtension.getScore() < totalScore){
//            throw new MaoshiShopBindException("用户积分不足，无法进行支付");
//        }
//
//    }
//    /**
//     *  积分订单事件如 积分购买商城的积分商品、积分购买优惠券
//     */
//    @EventListener(ScoreOrderEvent.class)
//    @Order(ConfirmOrderOrder.DEFAULT)
//    public void scoreCouponOrderListener(ScoreOrderEvent event) {
//        Integer scorePrice = event.getScore();
//        String userId = SecurityUtils.getUser().getUserId();
//        User user = userService.getById(userId);
//        if (user.getScore() == null || user.getScore() < scorePrice){
//            throw new MaoshiShopBindException("积分不足");
//        }
//
//        user.setScore(user.getScore() - scorePrice);
//        UserScoreRecord scoreRecord = new UserScoreRecord();
//        scoreRecord.setIoType(0);
//        scoreRecord.setConsumeType(event.getScoreRecordType().value());
//        if (Objects.equals(event.getScoreRecordType(), ScoreRecordType.RECORD_TYPE_NORMAL)) {
//            scoreRecord.setOrderNumber(String.valueOf(event.getSource()));
//        }
//        scoreRecord.setUserId(userId);
//        scoreRecord.setCreateTime(DateUtil.date());
//        scoreRecord.setScore(scorePrice);
//        userScoreRecordService.save(scoreRecord);
//        userService.updateById(user);
//    }
}
